﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using DevComponents.DotNetBar;
using NHTU;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace NOMFinalSettlement.Classes
{
    public class AppProcess
    {
        public void listBackupFile(DevComponents.DotNetBar.Controls.ListViewEx listViewFolder, string backupPath)
        {
            listViewFolder.Items.Clear();
            try
            {
                var fList = Directory.GetFiles(@"" + backupPath + "");
                var sort = from s in fList
                           orderby s descending
                           select s;
                foreach (string _filePath in sort)
                {
                    if (IsBakFile(_filePath))
                    {
                        var fileName = _filePath.Replace(backupPath+"\\","");
                        listViewFolder.Items.Add(fileName).SubItems.Add(fileName);
                    }
                }
            }
            catch { }

        }
        private bool IsBakFile(string filePath)
        {
            return filePath != null && filePath.EndsWith(".bak", StringComparison.Ordinal);
        }

        public string fileGeneral(string backupPath)
        {
            string fileGeneral = backupPath + "\\" + DateTime.Now.ToString("Backup-yyyyMMdd-HHmmss");
            try
            {
                if (! Directory.Exists(backupPath))
                {
                    Directory.CreateDirectory(backupPath);
                }
                return fileGeneral +".bak";
            }
            catch
            {
                return null;
            }
        }
        public void setIsLogin(bool use)
        {
            var _this = MainApp.Self;
            _this.ribbonPanelUse.Enabled = use;
            _this.appMenuNew.Visible = use;
            _this.appMenuOpen.Visible = use;
            _this.appMenuChangePassword.Visible = use;
            _this.appMenuProfile.Visible = use;
            _this.appMenuLogout.Visible = use;
            _this.btnUserManager.Enabled = use;
            _this.btnDataBackup.Enabled = use;
            _this.btnDataRestore.Enabled = use;
            _this.btnAppStyle.Enabled = use;

            if (true == use)
            {
                _this.ribbonTabUse.Checked = true;
                _this.appMenuLogin.Visible = false;
            }
            else
            {
                _this.ribbonTabHelp.Checked = true;
                _this.appMenuLogin.Visible = true;
            }
        }

        public void checkUserPermissions()
        {
            var _this = MainApp.Self;
            var per = _this.DBUSER;

            // Phân quyền hồ sơ
            _this.appMenuNew.Enabled = per.TiepNhanHoSo;
            _this.appMenuOpen.Enabled = per.TiepNhanHoSo;
            _this.btnAddNewProfile.Enabled = per.TiepNhanHoSo;
            _this.btnApplyProfile.Enabled = per.GiaoHoSo;
            _this.btnApplySign.Enabled = per.TrinhPheDuyet;
            _this.btnSignFinally.Enabled = per.PheDuyetQT;
            // Phân quyền báo cáo
            _this.btnReportExport.Enabled = per.BCTongHop;
            _this.btnReportAll.Enabled = per.BCTinhHinhQT;
            _this.btnReportNewProfile.Enabled = per.BCHoSoMoi;
            _this.btnReportNotFinish.Enabled = per.BCTinhHinhHSChuaQT;
            _this.btnReportNotFinishDetails.Enabled = per.BCChiTietHSChuaQT;
            _this.btnReportFinishDetails.Enabled = per.BCChiTietHSDaQT;
            // Phân quyền hệ thống
            _this.btnDataCommon.Enabled = per.DuLieuHeThong;
            _this.btnUserManager.Enabled = per.NguoiDung;
            _this.btnDataBackup.Enabled = per.SaoLuu;
            _this.btnDataRestore.Enabled = per.PhucHoi;
            _this.btnAppStyle.Enabled = per.GiaoDien;
        }

        public void setStyle(DevComponents.DotNetBar.eStyle style)
        {
            MainApp.Self.appStyle.ManagerStyle = style;
            this.saveStyle();
        }

        public void saveStyle()
        {
            var appCfg = new Properties.Settings();
            appCfg.AppSkin = MainApp.Self.appStyle.ManagerStyle;
            appCfg.Save();
        }

        public void callFormDialog(string fname)
        {
            string _namespace = GetNameSpace(fname);
            try
            {
                Type fType = Assembly.GetEntryAssembly().GetType(_namespace);
                Form f = (Form)Activator.CreateInstance(fType);
                f.StartPosition = FormStartPosition.CenterScreen;
                f.MinimizeBox = false;
                f.MaximizeBox = false;
                f.ShowDialog();
                f.ShowInTaskbar = false;
            }
            catch(Exception ex)
            {
                //MsgBox.Show(_namespace + " không tồn tại.", "Lỗi gọi Form", MsgBoxButton.Ok, MsgBoxIcon.Warning);
                MsgBox.Show(ex.Message, "Lỗi hệ thống", MsgBoxButton.Ok, MsgBoxIcon.Warning);
            }
        }

        public delegate void delegateCallForm(string str);
        public void callFormInsideTab(string fname)
        {
            var _self = MainApp.Self;

            if (_self.InvokeRequired)
            {
                _self.Invoke(new delegateCallForm(callFormInsideTab), new object[] { fname });
            }
            else
            {
                _self.loadingForm.Show();

                var tabControl = _self.tabControl;

                string _namespace = GetNameSpace(fname);
                try
                {
                    Type fType = Assembly.GetEntryAssembly().GetType(_namespace);
                    Form f = (Form)Activator.CreateInstance(fType);
                    if (this.__isTabOpen(tabControl, f.Text))
                    {
                        _self.loadingForm.Hide();
                        return;
                    }
                    tabControl.Visible = true;

                    var _tab = tabControl.CreateTab(f.Text);
                    f.FormBorderStyle = FormBorderStyle.None;
                    f.TopLevel = false;
                    f.Dock = DockStyle.Fill;
                    _tab.Name = fname;
                    _tab.AttachedControl.Controls.Add(f);
                    f.Show();
                    
                }
                catch (Exception ex)
                {
                    //MsgBox.Show(_namespace + " không tồn tại.", "Lỗi gọi Form", MsgBoxButton.Ok, MsgBoxIcon.Warning);
                    MsgBox.Show(ex.Message, "Lỗi hệ thống", MsgBoxButton.Ok, MsgBoxIcon.Warning);
                }
                tabControl.SelectedTabIndex = tabControl.Tabs.Count - 1;
                tabControl.AutoCloseTabs = true;
                tabControl.CloseButtonOnTabsVisible = true;
                _self.loadingForm.Hide();
            }
        }

        private string GetNameSpace(string fName)
        {
            Type derivedType = GetType();
            string _namespace = derivedType.Namespace;
            _namespace = _namespace.Substring(0, _namespace.IndexOf("."));
         
            return _namespace + "." + fName;

        }
        private bool __isTabOpen(DevComponents.DotNetBar.TabControl tabControl, string name)
        {
            int tabCounter = tabControl.Tabs.Count;

            for (int i = 0; i < tabCounter; i++)
            {
                if (tabControl.Tabs[i].Text == name)
                {
                    tabControl.SelectedTabIndex = i;
                    return true;
                }
            }
            return false;
        }

        public void setTabCloseItem(DevComponents.DotNetBar.TabControl tabControl)
        {
            if (tabControl.Tabs.Count < 1)
            {
                tabControl.Visible = false;
            }
        }
        public void removeAllTabs(DevComponents.DotNetBar.TabControl tabControl)
        {
            int tabCount = tabControl.Tabs.Count;
            int i = 0;
            while (i < tabCount)
            {
                ++i;
                tabControl.Tabs.RemoveAt(tabCount - i);   
            }
        }

        //Lấy ID từ Grid (Điều kiện ID ở cột đầu tiên)
        public int getIdGrid(DevComponents.DotNetBar.Controls.DataGridViewX grid, DataGridViewCellMouseEventArgs e, ContextMenuStrip ctMenu)
        {
            int id;
            try
            {
                grid.CurrentCell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex];
                grid.Rows[e.RowIndex].Selected = true;

                if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.Button == MouseButtons.Right)
                {
                    if (ctMenu != null)
                    {
                        //System.Drawing.Rectangle r = grid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                        //ctMenu.Show(grid, r.Left + e.X, r.Top + e.Y);
                        ctMenu.Show(Cursor.Position);
                    }

                    id = Convert.ToInt32(grid.Rows[e.RowIndex].Cells[0].Value.ToString());
                }
                else
                {
                    int rowIndex = Convert.ToInt32(grid.CurrentRow.Index);
                    id = Convert.ToInt32(grid.Rows[rowIndex].Cells[0].Value.ToString());
                }
            }
            catch
            {
                id = 0;
            }
            return id;
        }

        public void setStartUp(bool yes)
        {
            Microsoft.Win32.RegistryKey rkApp = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            string fileName = Application.ExecutablePath.ToString();
            string AppReg = System.IO.Path.GetFileNameWithoutExtension(fileName);
            //if (rkApp.GetValue(AppReg) == null)
            //{
             
            //}
            if (yes)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue(AppReg, fileName);
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue(AppReg, false);
            }
        }

        public void clientPermission()
        {
            // Make sure client has permissions 
            try
            {
                SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
                perm.Demand();
            }
            catch
            {
                throw new ApplicationException("No permission");
            }
        }

        public string crossText(Control c)
        {
            var _str = "";
            c.Invoke((MethodInvoker)delegate
            {
                _str = c.Text;
            });
            return _str;
        }
    }
}
